package com.speech.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.AppConfig;
import com.speech.MyApplication;
import com.speech.R;
import com.speech.activity.LoginActivity;
import com.speech.activity.MiningActivity;
import com.speech.activity.PropertyRankingActivity;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.entity.MyProperty;
import com.speech.entity.UserInfo;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.request.UserInfo_Data;
import com.speech.net.result.Property_Result;
import com.speech.result.Result;
import com.speech.utils.ClipBoardUtil;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;
import com.speech.utils.MissionNoobFinishState;
import com.speech.utils.PropertyAndUserInfoHolder;
import com.speech.utils.PropertyTodayDataHolder;
import com.speech.utils.StringFomatUtil;

import java.util.Calendar;

import retrofit2.Call;

public class HomeFragment extends Fragment {

    private SimpleDraweeView sdv_head;

    private ImageView img_audio;

    private TextView tv_pool_total_progress_num;
    private TextView tv_pool_total_num;
    private TextView tv_date_count;
    private TextView tv_nickname;
    private TextView tv_today_receive_coin;
    private TextView tv_total_coin;
    private TextView tv_today_sentence_count;
    private TextView tv_today_left;
    private ImageView img_ranking;
    private ProgressBar pb;
    private long lEndTime = 1539100800000L;
    private boolean isCreated = false;
    private String strTodayLeftTotal = "万(SPK)";
    private SweetAlertDialog dialog;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, null);

        _initView(view);

        isCreated = true;

        tv_nickname.setText(PropertyAndUserInfoHolder.getStrNickName(getActivity()) + "的资产");

        ////////在这里进行全局数据的初始化/////////
        _initData();
        /////////////////////////////////////


        img_audio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), MiningActivity.class));
            }
        });

//        img_ranking.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getActivity(), PropertyRankingActivity.class));
//            }
//        });

        return view;
    }


    private void _initData() {
        //获取用户资产，完成回在回调中获取用户读语料数，因为获取句子数要和用户资产接口返回的时间配合
        _get_user_property();

        // 以下这些操作只会在app运行过程中进行一次初始化操作
        if (!AppConfig.STATE_INIT) {

            AppConfig.STATE_INIT = true;

            //获取用户信息
            _get_user_info();

            //获取邀请码
            _get_invite_code();

            //获取新手任务完成状况，这是记录在本地的，所以卸载app后重装就会丢失记录
            MissionNoobFinishState.init(getActivity());
        }

    }

    private void _change_head_picture() {
        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
        String strBitmap_Base64 = (String) spf_helper.getData(PrefsConstant.KEY_USER_INFO_HEAD_PICTURE_BASE64, SharedPreferenceHelper.STR_TYPE_DEFAULT);


//        BitmapFactory.decodeByteArray();

        Uri uri = Uri.parse("res:///" + R.mipmap.ic_launcher);
        sdv_head.setImageURI(uri);
    }

    private void _get_invite_code() {

        //TODO: 接口请求
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(getActivity(), EnumReqestActionCode.获得邀请码地址, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(getActivity(), json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                ClipBoardUtil.strInviteCode = msg_s2c.strData.replace("{\"url\":\"", "").replace("\"}", "");
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//                new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText(msg_s2c.strMsgUI)
//                        .setConfirmText("OK")
//                        .show();
//            }
//        }));
    }

    private void _reset_app() {
        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
        spf_helper.clear();

        spf_helper = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_TODAY_DATA);
        spf_helper.clear();

        new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
                .setTitleText("发生未知错误，请重新登录!")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        sweetAlertDialog.dismiss();
                    }
                })
                .show();
    }

    private void _get_user_info() {

        //TODO: 接口请求 用户首页个人信息
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(getActivity(), EnumReqestActionCode.获得用户信息, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(getActivity(), json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UserInfo_Data userInfo = JsonProcessor.StcGetObject(UserInfo_Data.class, msg_s2c.strData);
//
//                SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
//                spf_helper.putData(PrefsConstant.KEY_USER_INFO_STRING_NICKNAME, userInfo.strNickName);
//
//                //如果用户设置了头像
//                if (userInfo.strUserPortrait != null && userInfo.strUserPortrait.length() > 10) {
////                    byte[] bytes = Base64.decode(userInfo.strUserPortrait, Base64.NO_WRAP);
////
////                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
////
////                    //TODO 头像重复保存
////                    String strImgUrl = (String) spf_helper.getData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,SharedPreferenceHelper.STR_TYPE_DEFAULT);
////                    if(!strImgUrl.equals(SharedPreferenceHelper.STR_TYPE_DEFAULT)){
////                        AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);
////                    }
////
////                    if (AppConfig.URI_HEAD_PICTURE == null) {
////                        strImgUrl = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null, null);
////                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,strImgUrl);
////                    }
////
////
////                    AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);
////
////                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
//
//                }
//
//                //获取完昵称就可以更新界面了
//                tv_nickname.setText(userInfo.strNickName + "的资产");
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));


        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<UserInfo>> call = MyApplication.getInstance().getApiService()
                .userInfo(uid, DeviceUtil.getDeviceID(getActivity()),token);
        call.enqueue(new BaseCallback<UserInfo>() {
            @Override
            public void onSuccess(UserInfo baseEntity) {
//                UserInfo_Data userInfo = JsonProcessor.StcGetObject(UserInfo_Data.class, baseEntity.getContent());

                SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
                spf_helper.putData(PrefsConstant.KEY_USER_INFO_STRING_NICKNAME, baseEntity.getNick_name());

                //如果用户设置了头像
//                if (userInfo.strUserPortrait != null && userInfo.strUserPortrait.length() > 10) {
//                    byte[] bytes = Base64.decode(userInfo.strUserPortrait, Base64.NO_WRAP);
//
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//
//                    //TODO 头像重复保存
//                    String strImgUrl = (String) spf_helper.getData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,SharedPreferenceHelper.STR_TYPE_DEFAULT);
//                    if(!strImgUrl.equals(SharedPreferenceHelper.STR_TYPE_DEFAULT)){
//                        AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);
//                    }
//
//                    if (AppConfig.URI_HEAD_PICTURE == null) {
//                        strImgUrl = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null, null);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,strImgUrl);
//                    }
//
//
//                    AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);
//
//                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);

//                }

                //获取完昵称就可以更新界面了
                tv_nickname.setText(baseEntity.getNick_name() + "的资产");
            }

            @Override
            public void onAbnormal(String msg) {

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }


    private void _get_user_total_sentence(final Long lCurrentTime) {

        //TODO: 接口请求
        //更新当前用户总句子数
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(getActivity(), EnumReqestActionCode.查询用户读文本信息, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(getActivity(), json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//
//                // 获得了当前句子总数，到此就可以认为初始化完成了
//                Property_Result property_rst = JsonProcessor.StcGetObject(Property_Result.class, msg_s2c.strData);
//
//                if (property_rst != null) {
//                    PropertyAndUserInfoHolder.update(property_rst);
//                }
//
//                PropertyTodayDataHolder.init(getActivity(), lCurrentTime);
//
//                tv_today_receive_coin.setText(StringFomatUtil.formatDouble(PropertyTodayDataHolder.getdToday_CoinReceive()));
//                tv_today_sentence_count.setText(PropertyTodayDataHolder.getiToday_ReadCount() + "");
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//                new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText(msg_s2c.strMsgUI)
//                        .setConfirmText("OK")
//                        .show();
//            }
//        }));
    }

    private void _initView(View view) {
        sdv_head = view.findViewById(R.id.sdv_home_head);
        img_audio = view.findViewById(R.id.img_home_audio_btn);

        tv_pool_total_progress_num = view.findViewById(R.id.tv_home_pool_total_progress_num);
        tv_pool_total_num = view.findViewById(R.id.tv_home_pool_total_num);
        tv_date_count = view.findViewById(R.id.tv_home_date_count);
        tv_today_receive_coin = view.findViewById(R.id.tv_home_today_recive_coin);
        tv_total_coin = view.findViewById(R.id.tv_home_user_total_coin);
        tv_today_sentence_count = view.findViewById(R.id.tv_home_today_sentence_count);
        tv_nickname = view.findViewById(R.id.tv_home_user_coin_title);

        tv_today_left = view.findViewById(R.id.tv_home_today_left_num);

        img_ranking = view.findViewById(R.id.img_home_ranking_icon);

        pb = view.findViewById(R.id.pb_home_today);
    }

    private void _get_user_property() {

        //TODO: 接口请求 资产明细
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(getActivity(), EnumReqestActionCode.查询资产, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(getActivity(), json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//
//                //财产数据每次启动的时候都会访问一次服务器进行初始化
//                Property_Result property_rst = JsonProcessor.StcGetObject(Property_Result.class, msg_s2c.strData);
//                PropertyAndUserInfoHolder.update(property_rst);
//                tv_total_coin.setText(StringFomatUtil.formatDouble(property_rst.dTotalProperty));
//
//                //上所倒计时
//                Calendar cal = Calendar.getInstance();
//                long lAppTime = cal.getTimeInMillis();
//                long lLeftTime = lEndTime - lAppTime;
//                long lLeftDay = (lLeftTime / 1000 / 60 / 60 / 24) + 1;
//                tv_date_count.setText(lLeftDay + "");
//
//                //第一期出矿程度
//                //TODO: 第一期出矿度
////                double dProportion = property_rst.dTotalMinalLeft / 50000000;
////                tv_pool_total_progress_num.setText(StringFomatUtil.formatDouble(dProportion));
//
//                //今日剩余
//                pb.setMax(_change_2_int(PropertyAndUserInfoHolder.getPropertyObject().dTotalToday));//最大值
//                String str = property_rst.dTotalMinalLeft + "";
//                int iTodayCurrent = Integer.valueOf(str.substring(0, str.indexOf(".")));
//                pb.setProgress(iTodayCurrent);
//
//                //更新今日剩余文本
//                _format_today_left(property_rst.dTotalMinalLeft, property_rst.dTotalToday);
//
//
//                //获取读语料数
//                _get_user_total_sentence(property_rst.lServerTime);
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//                new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText(msg_s2c.strMsgUI)
//                        .setConfirmText("OK")
//                        .show();
//            }
//
//        }));


        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(getActivity(), PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<MyProperty>> call = MyApplication.getInstance().getApiService()
                .myProperty(uid,DeviceUtil.getDeviceID(getActivity()),token);
        call.enqueue(new BaseCallback<MyProperty>() {
            @Override
            public void onSuccess(MyProperty baseEntity) {

//                //财产数据每次启动的时候都会访问一次服务器进行初始化
//                Property_Result property_rst = JsonProcessor.StcGetObject(Property_Result.class, baseEntity.getContent());
//                PropertyAndUserInfoHolder.update(property_rst);
//                tv_total_coin.setText(StringFomatUtil.formatDouble(property_rst.dTotalProperty));
//
//                //上所倒计时
//                Calendar cal = Calendar.getInstance();
//                long lAppTime = cal.getTimeInMillis();
//                long lLeftTime = lEndTime - lAppTime;
//                long lLeftDay = (lLeftTime / 1000 / 60 / 60 / 24) + 1;
//                tv_date_count.setText(lLeftDay + "");
//
//                //第一期出矿程度
//                //TODO: 第一期出矿度
////                double dProportion = property_rst.dTotalMinalLeft / 50000000;
////                tv_pool_total_progress_num.setText(StringFomatUtil.formatDouble(dProportion));
//
//                //今日剩余
//                pb.setMax(_change_2_int(PropertyAndUserInfoHolder.getPropertyObject().dTotalToday));//最大值
//                String str = property_rst.dTotalMinalLeft + "";
//                int iTodayCurrent = Integer.valueOf(str.substring(0, str.indexOf(".")));
//                pb.setProgress(iTodayCurrent);
//
//                //更新今日剩余文本
//                _format_today_left(property_rst.dTotalMinalLeft, property_rst.dTotalToday);
//
//
//                //获取读语料数
//                _get_user_total_sentence(property_rst.lServerTime);
            }

            @Override
            public void onAbnormal(String msg) {
                dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
                        .setTitleText(msg)
                        .setConfirmText("OK");
                dialog.show();

            }

            @Override
            public void onFailure(String msg) {
                dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
                        .setTitleText(msg)
                        .setConfirmText("OK");
                dialog.show();

            }
        });
    }

    private int _change_2_int(Double dTotalToday) {

        String str = "0.0";
        if (dTotalToday != null) {
            str = dTotalToday + "";
        }
        str = str.substring(0, str.indexOf("."));

        return Integer.valueOf(str);
    }

    private void _format_today_left(Double dTotalMinalLeft, Double dTodayTotalMinal) {
        if (dTotalMinalLeft != null && dTodayTotalMinal != null && dTodayTotalMinal > 0) {
            String str_left = null;
            String str_total = null;

            if (dTotalMinalLeft >= 10000) {
                Double d = dTotalMinalLeft / 10000;
                str_left = StringFomatUtil.formatDouble(d) + "万";
            } else if (dTotalMinalLeft < 10000) {
                str_left = StringFomatUtil.formatDouble(dTotalMinalLeft);
                str_left = str_left.substring(0, str_left.indexOf("."));
            }

            String strTotal = StringFomatUtil.formatDouble(dTodayTotalMinal / 10000);
            str_total = strTotal.substring(0, strTotal.indexOf("."));


            tv_today_left.setText(str_left + "/" + str_total + strTodayLeftTotal);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AppConfig.URI_HEAD_PICTURE != null) {
            sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
        }

        if (!isCreated) {
            _get_user_property();
        }

        tv_nickname.setText(PropertyAndUserInfoHolder.getStrNickName(getActivity()) + "的资产");
        tv_today_receive_coin.setText(StringFomatUtil.formatDouble(PropertyTodayDataHolder.getdToday_CoinReceive()));
        tv_today_sentence_count.setText(PropertyTodayDataHolder.getiToday_ReadCount() + "");
        tv_total_coin.setText(StringFomatUtil.formatDouble(PropertyAndUserInfoHolder.getPropertyObject().dTotalProperty));

        Property_Result property = PropertyAndUserInfoHolder.getPropertyObject();
        _format_today_left(property.dTotalMinalLeft, property.dTotalToday);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (!isCreated) {
            return;
        }

        if (isVisibleToUser) {
            tv_nickname.setText(PropertyAndUserInfoHolder.getStrNickName(getActivity()) + "的资产");
            tv_today_receive_coin.setText(StringFomatUtil.formatDouble(PropertyTodayDataHolder.getdToday_CoinReceive()));
            tv_today_sentence_count.setText(PropertyTodayDataHolder.getiToday_ReadCount() + "");
            tv_total_coin.setText(StringFomatUtil.formatDouble(PropertyAndUserInfoHolder.getPropertyObject().dTotalProperty));

            Property_Result property = PropertyAndUserInfoHolder.getPropertyObject();
            _format_today_left(property.dTotalMinalLeft, property.dTotalToday);

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
    }
}
